﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using MAPIdotnet;

namespace OutlookHub.Models
{
    public class Folder : IDisposable
    {
        private IMAPIFolder folder;

        public IMAPIFolderID Id { get; private set; }

        public string Name { get { return folder.DisplayName; } }

        public int SubFolderCount { get { return folder.NumSubFolders; } }

        public int MailCount { get { return folder.NumSubItems; } }

        public int Level { get; private set; }

        public Store Store { get; private set; }


        public Folder(IMAPIFolderID id, Store store)
            : base()
        {
            if (id == null) throw new ArgumentNullException("id");
            this.Id = id;
            this.Store = store;
            folder = Id.OpenFolder();
        }

        public void Dispose()
        {
            if (folder != null) folder.Dispose();
            GC.SuppressFinalize(this);
        }

        ~Folder()
        {
            Dispose();
        }


        public IMAPIMessageID[] GetNextMessages()
        {
            return folder.GetNextMessageIds(folder.NumSubItems);
        }

        /// <summary>
        /// Gets all messages.
        /// </summary>
        public IEnumerable<Message> Messages
        {
            get
            {
                //var ids = folder.GetNextMessageIds(folder.NumSubItems);
                var ids = folder.GetNextMessages(folder.NumSubItems);
                return ids.Select(id => Message.CreateMessage(id));
            }
        }

        /// <summary>
        /// Gets all sub folders.
        /// </summary>
        public IEnumerable<Folder> SubFolders
        {
            get
            {
                var ids = folder.GetSubFolders(folder.NumSubFolders);
                return ids.Select(id => Store.GetFolder(id));
            }
        }
    }
}
